import React, { useMemo } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useSelector } from 'react-redux'
import { ArrowLeft, MoreO, DeleteO } from '@react-vant/icons';
import { Popup, Dialog, Toast } from 'react-vant';
import './style/DetailShow.css'

interface Product {
  id: number;
  title: string;
  image: string;
  cateid: string;
}

interface Collection {
  _id: string;
  name: string;
  img: string;
}

interface RootState {
  show: Product[];
}

export default function DetailShow() {
  const location = useLocation()
  const navigate = useNavigate()
  const data = location.state as Collection
  const [showMore, setShowMore] = React.useState(false)

  const show = useSelector((state: RootState) => state.show)
  
  const newlist = useMemo(() => {
    return show.filter(item => item.cateid === data._id)
  }, [show, data._id])

  const handleDelete = (product: Product) => {
    Dialog.confirm({
      title: '确认删除',
      message: '确定要从收藏夹中删除这个商品吗？',
    }).then(() => {
      // 这里添加删除逻辑
      Toast.success('删除成功')
    })
  }

  return (
    <div className="detail-show-page">
      <div className='navigator'>
        <ArrowLeft onClick={() => navigate('/app/cang')} />
        <h2>{data.name}</h2>
        <MoreO onClick={() => setShowMore(true)} />
      </div>

      <div className="collection-content">
        {newlist.length === 0 ? (
          <div className="empty-state">
            <p>暂无收藏商品</p>
          </div>
        ) : (
          <div className="product-grid">
            {newlist.map((item) => (
              <div key={item.id} className="product-card">
                <div className="product-image" onClick={() => navigate('/detailCar', { state: item })}>
                  <img src={item.image} alt={item.name} />
                </div>
                <div className="product-info">
                  <h3 className="product-title">{item.name}</h3>
                  <DeleteO 
                    className="delete-icon"
                    onClick={(e) => {
                      e.stopPropagation()
                      handleDelete(item)
                    }}
                  />
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      <Popup
        visible={showMore}
        position="bottom"
        round
        onClose={() => setShowMore(false)}
      >
        <div className="more-actions">
          <div className="action-item" onClick={() => {
            // 添加编辑收藏夹功能
            setShowMore(false)
          }}>
            编辑收藏夹
          </div>
          <div className="action-item danger" onClick={() => {
            Dialog.confirm({
              title: '确认删除',
              message: '确定要删除这个收藏夹吗？',
            }).then(() => {
              // 添加删除收藏夹功能
              setShowMore(false)
              navigate('/app/cang')
            })
          }}>
            删除收藏夹
          </div>
        </div>
      </Popup>
    </div>
  )
}
